package com.lollipop.synthential.algorithm;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: J.K
 * @Date: 2022-07-29 14:41
 * @Description: 轮询加权算法
 */
@Slf4j
public class RoundRibbonWeight {
    private static AtomicInteger requestCount = new AtomicInteger(0);

    public static String getServer(){
        int weightTotal = 0;
        for (Integer weight : WeightServers.WEIGHT_SERVERS.values()) {
            weightTotal += weight;
        }

        String targetServer = "";
        int index = requestCount.get() % weightTotal;
        requestCount.incrementAndGet();

        for (String server : WeightServers.WEIGHT_SERVERS.keySet()) {
            Integer weight = WeightServers.WEIGHT_SERVERS.get(server);
            if (weight > index){
                targetServer = server;
                break;
            }
            index = index - weight;
        }
        return targetServer;
    }

    public static void main(String[] args){
        for (int i = 1; i <= 10; i++){
            log.info("第[{}]个请求，服务节点：[{}]", i, RandomRibbon.getServer());
        }
    }
}
